//
//  WeatherViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/17.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "WeatherViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface WeatherViewController ()<CLLocationManagerDelegate>
{
    CLLocationManager *locationmanager;//定位服务
    NSString *currentCity;//当前城市
    NSString *strlatitude;//经度
    NSString *strlongitude;//纬度
}

@property (nonatomic, weak)UIButton * backButton;
@property (nonatomic, weak)UIImageView * backImageView;
@property (nonatomic, strong)UILabel * titleLabel;
@property (nonatomic, strong)UILabel * localLabel;
@property (nonatomic, strong)UILabel * weatherLabel;
@property (nonatomic, strong)UILabel * dateLabel;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, strong)UILabel * todayLabel;
@property (nonatomic, strong)UILabel * weatherTLabel;
@property (nonatomic, strong)UILabel * torrowLabel;
@property (nonatomic, strong)UILabel * weatherTTLabel;

@end

@implementation WeatherViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    [self getLocation];
}

-(void)getLocation
{
    //判断定位功能是否打开
    if ([CLLocationManager locationServicesEnabled]) {
        locationmanager = [[CLLocationManager alloc]init];
        locationmanager.delegate = self;
        [locationmanager requestAlwaysAuthorization];
        currentCity = [NSString new];
        [locationmanager requestWhenInUseAuthorization];
        
        //设置寻址精度
        locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
        locationmanager.distanceFilter = 5.0;
        [locationmanager startUpdatingLocation];
    }
}

#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    //设置提示提醒用户打开定位服务
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"允许定位提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:nil];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [locationmanager stopUpdatingHeading];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //打印当前的经度与纬度
//    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);

    //反地理编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            self->currentCity = placeMark.locality;
            if (!self->currentCity) {
                self->currentCity = @"无法定位当前城市";
            }

            self.localLabel.text = [NSString stringWithFormat:@"%@ %@",placeMark.country,self->currentCity];
            
            NSString * city = [self->currentCity substringToIndex:([self->currentCity length] - 1)];
            
            NSString * str = [NSString stringWithFormat:@"/v1/weather/query?key=276cd36bb45f0&city=%@",city];
            
            NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
            NSString *encodeUrl = [str stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet];
            
            [[MobNetworkingTool sharedTools]  GET:encodeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSArray * arr = responseObject[@"result"];
                NSDictionary * dict = arr.firstObject;
                
                self.titleLabel.text = [NSString stringWithFormat:@"%@",dict[@"weather"]];
                self.weatherLabel.text = [NSString stringWithFormat:@"%@",dict[@"temperature"]];
                self.dateLabel.text = [NSString stringWithFormat:@"%@",dict[@"date"]];
                
                NSArray * future = dict[@"future"];
                
                NSDictionary * todayDict = future.firstObject;
                NSDictionary * nextDatDict = future[1];
                
                self.todayLabel.text = todayDict[@"week"];
                self.weatherTLabel.text = todayDict[@"temperature"];
                self.torrowLabel.text = nextDatDict[@"week"];
                self.weatherTTLabel.text = nextDatDict[@"temperature"];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
                NSLog(@"error==%@",error);
            }];
        }
    }];
}


- (void)setupUI{
    
    self.view.backgroundColor = WHITE_COLOR;
    
    
    UIImageView * backImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    
    backImageView.image = ImageNamed(@"edwqe5453");
    backImageView.userInteractionEnabled = YES;
    
    self.backImageView = backImageView;
    
    [self.view addSubview:self.backImageView];
    
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(25 * SCREENH6, 35 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    self.backButton = backButton;
    
    [self.backImageView addSubview:self.backButton];
    
    
    self.titleLabel = [UILabel new];
    
    self.titleLabel.textColor = WHITE_COLOR;
    self.titleLabel.font = [UIFont systemFontOfSize:22 * SCREENH6];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"----";
    
    [self.backImageView addSubview:self.titleLabel];
    
    
    self.localLabel = [UILabel new];
    
    self.localLabel.textColor = WHITE_COLOR;
    self.localLabel.font = [UIFont systemFontOfSize:17 * SCREENH6];
    self.localLabel.textAlignment = NSTextAlignmentCenter;
    self.localLabel.text = @"----";
    
    [self.backImageView addSubview:self.localLabel];
    
    
    self.weatherLabel = [UILabel new];
    
    self.weatherLabel.textColor = WHITE_COLOR;
    self.weatherLabel.font = [UIFont boldSystemFontOfSize:75 * SCREENH6];
    self.weatherLabel.textAlignment = NSTextAlignmentCenter;
    self.weatherLabel.text = @"32";
    
    [self.backImageView addSubview:self.weatherLabel];
    
    
    self.dateLabel = [UILabel new];
    
    self.dateLabel.textColor = WHITE_COLOR;
    self.dateLabel.font = [UIFont systemFontOfSize:16 * SCREENH6];
    self.dateLabel.textAlignment = NSTextAlignmentCenter;
    self.dateLabel.text = @"----";
    
    [self.backImageView addSubview:self.dateLabel];
    
    
    UIView * bottomView = [UIView new];
    
    bottomView.backgroundColor = WHITE_COLOR;
    
    self.bottomView = bottomView;
    
    [self.backImageView addSubview:self.bottomView];
    
    
    self.todayLabel = [UILabel new];
    
    self.todayLabel.textColor = ColorWithRGB(0x41CAFF);
    self.todayLabel.font = [UIFont boldSystemFontOfSize:17 * SCREENH6];
//    self.weatherLabel.textAlignment = NSTextAlignmentCenter;
    self.torrowLabel.text = @"====";
    
    [self.bottomView addSubview:self.todayLabel];
    
    self.weatherTLabel = [UILabel new];
    
    self.weatherTLabel.textColor = ColorWithRGB(0x41CAFF);
    self.weatherTLabel.font = [UIFont boldSystemFontOfSize:17 * SCREENH6];
    self.weatherTLabel.textAlignment = NSTextAlignmentRight;
    self.weatherTLabel.text = @"====";
    
    [self.bottomView addSubview:self.weatherTLabel];
    
    
    self.torrowLabel = [UILabel new];
    
    self.torrowLabel.textColor = ColorWithRGB(0xA6A6A6);
    self.torrowLabel.font = [UIFont boldSystemFontOfSize:17 * SCREENH6];
    //    self.weatherLabel.textAlignment = NSTextAlignmentCenter;
    self.torrowLabel.text = @"====";
    
    [self.bottomView addSubview:self.torrowLabel];
    
    self.weatherTTLabel = [UILabel new];
    
    self.weatherTTLabel.textColor = ColorWithRGB(0xA6A6A6);
    self.weatherTTLabel.font = [UIFont boldSystemFontOfSize:17 * SCREENH6];
    self.weatherTTLabel.textAlignment = NSTextAlignmentRight;
    self.weatherTTLabel.text = @"====";
    
    [self.bottomView addSubview:self.weatherTTLabel];
}


- (void)viewDidLayoutSubviews{
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(120 * SCREENH6);
    }];
    
    [self.localLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(13 * SCREENH6);
    }];
    
    [self.weatherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.localLabel.mas_bottom).offset(40 * SCREENH6);
    }];
    
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.weatherLabel.mas_bottom).offset(18 * SCREENH6);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.backImageView);
        make.height.mas_equalTo(134 * SCREENH6);
    }];
    
    [self.todayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.bottomView).offset(25 * SCREENH6);
        make.top.mas_equalTo(self.bottomView).offset(20 * SCREENH6);
    }];
    
    [self.weatherTLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.todayLabel);
        make.trailing.mas_equalTo(self.bottomView).offset(-20 * SCREENH6);
    }];
    
    [self.torrowLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.todayLabel);
        make.top.mas_equalTo(self.todayLabel.mas_bottom).offset(50 * SCREENH6);
    }];
    
    [self.weatherTTLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.torrowLabel);
        make.trailing.mas_equalTo(self.weatherTLabel);
    }];
}
- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
